/**
 * @file
 * @auth jinguangguo
 * @date 2017/07/27
 */


import Vue from 'vue';
import './FileUpload.scss';
import tpl from './FileUpload.html';
import commonService from '../../common/commonService';
import lib from '../../common/lib';
import filter from '../../../grsc-base/util/filter';
import Loading from '../../../grsc-base/component/Loading.vue'

// const IMG_PRE_SUFFIX = '/exchangeApi/common/photo?name=';
const IMG_PRE_SUFFIX = 'http://ov65fan4t.bkt.clouddn.com/';
// const IMG_AFTER_SUFFIX = '?imageView2/1/w/160/h/160';

/**
 * 得到文件格式
 * @param path
 * @returns {string}
 */
function getFileSuffix(path) {
    let index = path.lastIndexOf('.');
    return path.substr(index + 1).toLowerCase();
}

/**
 * 判断文件是否是图片
 * @param path
 * @returns {boolean}
 */
function isFileOk(path) {
    let suffix = getFileSuffix(path);
    if (suffix === 'jpg' || suffix === 'jpeg' || suffix === 'png') {
        return true;
    }
    return false;
}

function stringifyHeader(param) {
    let results = [];
    if ($.isEmptyObject(param) === true) {
        return '';
    }
    $.map(param, (value, key) => {
        let valueTemp = window.encodeURIComponent(value);
        results.push(`${key}=${valueTemp}`);
    });
    return results.join(',');
}

function getAuthHeader(param) {
    let headers = {
        'accept-language': 'zh-CN'
    };
    let accountNo = window.localStorage.getItem('account-no');
    let auth = {
        'account-no': accountNo
    };

    if ($.isEmptyObject(auth) === false) {
        headers.authorization = stringifyHeader(auth);
    }
    return headers;
}

export default Vue.extend({
    name: "FileUpload",
    template: tpl,
    components: {
        Loading
    },
    data() {
        return {
            img: '',
            isLoading: false,
        }
    },
    props: {
        clazz: String,
        type: {
            type: String,
            default: 'public'
        },
        maxSize: {
            type: Number,
            default: 2    // 单位是KB
        },
        onFileClick: {
            type: Function,
            default() {

            }
        },
        onFileChange: {
            type: Function,
            default() {

            }
        },
        onShowError: {
            type: Function,
            default(msg) {
                window.error(msg);
            }
        },
        onFileUploaded: {
            type: Function,
            default() {

            }
        }
    },
    computed: {},
    created() {

    },
    methods: {

        clickFileInput() {
            this.$emit('cancelTip');
            this.onFileClick();
        },

        changeFileInput($event) {
            let that = this;
            let dom = this.$refs.input;
            let path = $event.target.value;
            let file = dom.files[0];

            // 图片格式已经在input框上面进行了限制
            if (isFileOk(path) === false) {
                this.onShowError('请选择正确的图片格式');
                return;
            }

            if (file.size / 1024 / 1024 > this.maxSize) {
                // debugger;
                this.onShowError('图像不得超过' + this.maxSize + 'M');
                return;
            }

            let reader = new FileReader();
            reader.onload = function (e) {
                let imgBase64 = this.result;

                that.isLoading = true;

                let form = new FormData();
                form.append('Content-Type', file.type || 'application/octet-stream');
                form.append('file', file);
                $.ajax({
                    url: `/exchangeApi/common/upload-photo/${that.type}`,
                    type: 'POST',
                    cache: false,
                    headers: getAuthHeader(),
                    data: form,
                    processData: false,
                    contentType: false
                }).done(rep => {
                    if (rep.code === window.CODE.SUCCESS) {
                        that.img = imgBase64;
                        that.onFileUploaded(rep.data.name, that.img);
                    } else {
                        window.error(rep.msg);
                    }
                }).fail(function(res) {
                    window.error(res.statusText);
                }).always(() => {
                    that.isLoading = false;
                });
            };
            reader.readAsDataURL(file);



            // 技术方案说明：http://www.jianshu.com/p/46e6e03a0d53


            $event.target.value = '';
        }

    }
});